﻿using System.Threading.Channels;

namespace JonPause
{
    internal class Program
    {
        static readonly Channel<object> channel = Channel.CreateBounded<object>(1);
        static TaskCompletionSource tcs1 = new TaskCompletionSource();
        static async Task Main(string[] args)
        {
            var tcs = new TaskCompletionSource();
            Task.Run(async () =>
            {
                await Task.Delay(10 * 1000);
                tcs?.TrySetResult();
            });
            Block(tcs.Task);

            await CheckPoint();
            Console.WriteLine("Hello, World!");
        }

        static int state = 0b10;

        public static void Block(Task task)
        {

            if ((Interlocked.CompareExchange(ref state, 0, 0) & 1) == 1)
            {
                throw new InvalidOperationException("Processing has completed.");
            }

            if (!channel.Writer.TryWrite(task))
            {
                throw new InvalidOperationException("Block was not possible!");
            }
            Console.WriteLine("11111111111111111111111");
        }



        public static async Task CheckPoint()
        {
            if ((Interlocked.CompareExchange(ref state, 0, 0) & 1) == 1)
            {
                throw new OperationCanceledException();
            }

            if (channel.Reader.TryRead(out var task))
            {
                await ((Task)task).ConfigureAwait(false);//代码卡在 await ((Task)task).ConfigureAwait(false) 的唯一原因是 ​​tcs.Task 未完成​​，而 tcs.TrySetResult() 是触发其完成的必要条件。若删除或未调用此方法，异步等待将永久挂起
            }
        }
    }
}
